package com.terren.schelude.work;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.collections.CollectionUtils;

import com.terren.common.entity.WxArticle;
import com.terren.common.util.CommonUtil;
import com.terren.config.SysConfig;
import com.terren.db.service.WxArticleService;

public class WxArticleWork extends BasicWork implements Runnable {

    public WxArticleWork(CountDownLatch countDownLatch){
    	super();
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
    	WxArticleService wxArticleService = CommonUtil.getBean(WxArticleService.class);
  
        try {
        	
            log.info(Thread.currentThread().getName() + "启动@" + System.currentTimeMillis());
            while(true){
            	WxArticle art = new WxArticle();
            	art.setLimit(SysConfig.LIMIT);
	            List<WxArticle> list = wxArticleService.getArticleList(art);
	            if(CollectionUtils.isEmpty(list)) {
	        		break;
	        	}
	    		List<WxArticle> dealList = new ArrayList<WxArticle>();
	    		int total = list.size();
        		int i = 1;
        		for(WxArticle a : list) {
        			//调接口
        			log.info("当前第 "+i+"微信文章正在调用接口,本轮共计"+total+"篇微信文章");
        			i++;
        			List<String> keywords = wxArticleService.getKeywords(a);
        			if(CollectionUtils.isNotEmpty(keywords)) {
        				Boolean flag = CommonUtil.keywords(a.getContent(),keywords);
            			if(flag) {
            				Integer score = getScore(a.getContent());
                			if(score !=-1 && findKeyword(a.getContent(), set)) {
                				a.setOpinion_analysis(score);
                				StringBuilder sb = new StringBuilder();
                				int m = keywords.size();
                				for(int k=1;k<=m;k++) {
                					if(k==m) {
                						sb.append(keywords.get(k-1));	
                					}else {
                						sb.append(keywords.get(k-1)).append(",");
                					}
                					
                				}
                				a.setKeyword(sb.toString());
                				dealList.add(a);
                			}
            			}
        			}
	    			
	    		}
        		if(CollectionUtils.isNotEmpty(dealList)) {
        			opinionAnalysisService.saveWxArticles(dealList);
        		}
	    		wxArticleService.updateDoneStatus(list);
    		}
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
        	if(countDownLatch !=null)
        		countDownLatch.countDown();
        	log.info("微信文章调用接口完成......");
		} 
    }
}
